package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.ruoyi.business.dao.InventoryDao;
import com.ruoyi.business.domain.Inventory;
import com.ruoyi.business.dto.CardetailDto;
import com.ruoyi.business.dto.InventoryDto;
import com.ruoyi.business.service.IInventoryService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.CardetailDao;
import com.ruoyi.business.domain.Cardetail;
import com.ruoyi.business.service.ICardetailService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import com.ruoyi.business.domain.CarMain;
import org.springframework.data.domain.PageImpl;

/**
 * cardetailService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-07-15
 */
@Transactional(readOnly = true)
@Service
public class CardetailServiceImpl implements ICardetailService {

    @Autowired
    private CardetailDao cardetailDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IInventoryService  inventoryService;
    @Autowired
    private InventoryDao  inventoryDao;

    /**
     * 查询cardetail
     *
     * @param id cardetailID
     * @return cardetail
     */
    @Override
    public Cardetail findById(Integer id) {
        return cardetailDao.findById(id).get();
    }

    /**
     * 分页查询cardetail列表
     *
     * @param req cardetail
     * @return cardetail
     */
    @Override
    public Page<CardetailDto> findCardetailPage(CardetailDto req) {
        Specification<Cardetail> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.ASC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("id"));
        Page<Cardetail> page = cardetailDao.findAll(example, pageable);
         List<Cardetail>  list=  page.getContent();
        SysUser sysUser=    tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
         List<CardetailDto>  dtoList=new ArrayList<>();
          for(Cardetail cardetail:list){
            String cinvcode=    cardetail.getCinvcode().getCinvcode();
              InventoryDto  inventoryDto=new InventoryDto(cinvcode);
              Page<InventoryDto> inventoryDtoPage=    inventoryService.findInventoryPage(inventoryDto);
               inventoryDto= inventoryDtoPage.getContent().get(0);
              CardetailDto  cardetailDto=new CardetailDto();
              BeanUtils.copyProperties(inventoryDto,cardetailDto);
              cardetailDto.setId(cardetail.getId());
              cardetailDto.setOrderNum(cardetail.getOrderNum());
              BigDecimal  rate=inventoryDao.getCustomerRate(sysUser.getUserId());
              cardetailDto.setRate(rate);
              cardetailDto.setPrice(inventoryDto.getSaleprice().multiply(rate).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
              cardetailDto.setAmount(cardetail.getOrderNum().multiply(cardetailDto.getPrice()).setScale(2,BigDecimal.ROUND_HALF_UP));
              if(cardetailDto.getItaxrate()==null){
                  cardetailDto.setItaxrate(new BigDecimal(13));
              }
              cardetailDto.setMoney(cardetailDto.getAmount().divide(
                      (new BigDecimal(1)).add(cardetailDto.getItaxrate().divide(new BigDecimal(100)) .setScale(2,BigDecimal.ROUND_HALF_UP)),2,BigDecimal.ROUND_HALF_UP)

              );
              cardetailDto.setTax(cardetailDto.getAmount().subtract(cardetailDto.getMoney()));
              cardetailDto.setMainid(cardetail.getMainid());
              dtoList.add(cardetailDto);
          }
        Page<CardetailDto> newPage = new PageImpl<>(dtoList, pageable, page.getTotalElements());
        return newPage;
    }

    /**
     * 分页查询cardetail列表
     *
     * @param req cardetail
     * @return cardetail
     */
    @Override
    public List<Cardetail> findCardetailList(CardetailDto req) {
        Specification<Cardetail> example = formatQueryParams(req);
        List<Cardetail> list = cardetailDao.findAll(example, Sort.by(Sort.Direction.ASC,"id"));
        return list;
    }

    private Specification<Cardetail> formatQueryParams(CardetailDto req){
        Specification<Cardetail> example = new Specification<Cardetail>() {
            private static final long serialVersionUID = 1L;
            @Override
            public Predicate toPredicate(Root<Cardetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (null != req.getId()){
                    Predicate pre = cb.equal(root.get("id").as(Integer.class), req.getId());
                    list.add(pre);
                }

                //查询该用户的购物车商品信息
                SysUser sysUser=    tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                if (null != sysUser &&  !sysUser.isAdmin()) {
                    Join<Cardetail, CarMain> mainJoin = root.join("mainid", JoinType.INNER);
                    Join<CarMain, SysUser> userJoin = mainJoin.join("userId", JoinType.INNER);
                    Predicate pre = cb.equal(userJoin.get("userId"), sysUser.getUserId());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCinvcode())){
                    Predicate pre = cb.equal(root.get("cinvcode").get("cinvcode"), req.getCinvcode());
                    list.add(pre);
                }

                if (null != req.getCinvname()){
                    Join<Cardetail, Inventory>  inventory = root.join("cinvcode", JoinType.INNER);
                    Predicate pre = cb.like(inventory.get("cinvname").as(String.class), "%"+ req.getCinvname()+"%");
                    list.add(pre);
                }
                if (null != req.getCinvstd()){
                    Join<Cardetail, Inventory>  inventory = root.join("cinvcode", JoinType.INNER);
                    Predicate pre = cb.like(inventory.get("cinvstd").as(String.class), "%"+ req.getCinvstd()+"%");
                    list.add(pre);
                }

                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）cardetail
     *
     * @param cardetail cardetail
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Cardetail cardetail) {
        cardetailDao.save(cardetail);
    }




    /**
     * 删除cardetail信息
     *
     * @param id cardetailID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCardetailById(Integer id) {
         cardetailDao.deleteById(id);
    }
}
